package com.gooagoo.supercrm.net;


import com.gooagoo.supercrm.BuildConfig;
import com.gooagoo.supercrm.constant.ConfigInfo;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by admin on 2016/7/15.
 */
public class RetrofitManager {

    private static RetrofitManager manager;
    private static ApiService service;
    // 网络请求超时时间
    private static int DEFAULT_TIMEOUT = 5;

    private RetrofitManager() {
        init();
    }

    public static RetrofitManager getInstance() {
        if (manager == null) {
            synchronized (RetrofitManager.class) {
                if (manager == null) {
                    manager = new RetrofitManager();
                }
            }
        }
        return manager;
    }

    public ApiService getService() {
        return service;
    }

    public static void init() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                .retryOnConnectionFailure(true);//错误重连
        //调试模式打印Log日志
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        if(BuildConfig.DEBUG){
            //显示日志
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }else {
            logInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
        }
        builder.addInterceptor(logInterceptor);
        OkHttpClient client=builder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(ConfigInfo.getHOST())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        service = retrofit.create(ApiService.class);
    }
}
